package com.wanpinghui.supplier.widgets;

import android.content.Context;
import android.os.Build;
import android.support.annotation.IntDef;
import android.support.v4.content.ContextCompat;
import android.support.v4.util.LongSparseArray;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.wanpinghui.supplier.R;

import com.wanpinghui.wphlibrary.model.user.bean.BaseNameSelectBean;
import com.wanpinghui.wphlibrary.model.user.bean.SkillBean;
import com.yunshl.yunshllibrary.utils.LogUtils;
import com.yunshl.yunshllibrary.utils.TextUtil;

import org.xutils.common.util.DensityUtil;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.List;


/***
 * 功能描述:
 * 作者:qiujialiu
 * 时间:2016/12/27
 * 版本:1.0
 ***/

public class GoodFormatView extends LinearLayout {
    private static final String TAG = "GoodFormatView";
    private Context mContext;
    private LinearLayout mCurrentLayout;
    private LongSparseArray<TextView> mTextViewMap;
    private List<? extends BaseNameSelectBean> datas;
    private OnItemClickListenr mListener;
    private boolean haveAddItem;
    private int type = 0;

    private float baseScale = 1;

    private int bgResource;
    private int textColor;
    private int parentPadding;
    private int width;
    private int minWidth;

    private int maxSelect;

    private int isSelectnum;

    private String AddlastStr = "+";


    public int getMaxSelect() {
        return maxSelect;
    }

    public void setMaxSelect(int maxSelect) {
        this.maxSelect = maxSelect;
    }

    public String getAddlastStr() {
        return AddlastStr;
    }

    public void setAddlastStr(String addlastStr) {
        AddlastStr = addlastStr;
    }



    @IntDef ({
        0,//多选
        1//单选
    })
    @Retention(RetentionPolicy.SOURCE)
    @interface FormatType {}

    public void setType(@FormatType int type) {
        this.type = type;
    }

    public void notifyDataSetChange() {
        refreshView();
    }

    public GoodFormatView(Context context) {
        super(context);
        init(context);
    }


    public GoodFormatView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public GoodFormatView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    public void setParentPadding(float padding) {
        parentPadding = DensityUtil.dip2px(padding*2);
    }

    public void setWidth(float width) {
        this.width = DensityUtil.dip2px(width);
        LogUtils.w("GoodFormatView", "set width : "+width);
    }

    public void setScale(float scale) {
        this.baseScale = scale;
    }

    public void setData(List<? extends BaseNameSelectBean> datas){
        mTextViewMap.clear();
        this.datas = datas;
        refreshView();
    }

    public void setBgResource(int resource) {
        this.bgResource = resource;
    }

    public void setTextColor(int colorResource) {
        this.textColor = colorResource;
    }

    public void setHaveAddItem(boolean haveAddItem) {
        this.haveAddItem = haveAddItem;
    }



    private void refreshView() {
        removeAllViews();
        int viewWidth = (width == 0 ? DensityUtil.getScreenWidth() : width);
        minWidth = (int) ((viewWidth - (DensityUtil.dip2px(57.5f)))/4f);
        LogUtils.w("GoodFormatView", "minWidth : "+minWidth);
        if (getDataSize() >0){
            for (int i=0;i<datas.size();i++){
            //    if (goodsBean.getType_() == GoodsType.TYPE_PRE_SELL){
                SkillBean bean = (SkillBean) datas.get(i);
                    addView(bean.getSkill_name(),bean.is_select_(),i,true);
//                }else {
//                    addView(datas.get(i).getName_(),datas.get(i).is_select_(),i,datas.get(i).isCanClick());
//                }

            }
        }
        if (haveAddItem) {
            addView(getAddlastStr(), false, getDataSize(),true);
        }
    }

    private void addView(String content,boolean isSelected,int i,boolean isCanClick) {
        if (getChildCount()==0){
            LogUtils.w(TAG,"第一次添加View");
            LinearLayout linear = createLinearLayout();
            TextView textView = createTextView();
            mTextViewMap.put(i,textView);
            textView.setText(content);
            if (isSelected){
                textView.setSelected(true);
            }else {
                textView.setSelected(false);
            }
            if (isCanClick) {
                textView.setEnabled(true);
            }else {
                textView.setEnabled(false);
            }

            addClickListener(textView,i);
            linear.addView(textView);
            addView(linear);
        }else {
            TextView textView = createTextView();
            textView.setText(content);
            if (isSelected){
                textView.setSelected(true);
            }else {
                textView.setSelected(false);
            }
            if (isCanClick) {
                textView.setEnabled(true);
            }else {
                textView.setEnabled(false);
            }
            mTextViewMap.put(i,textView);
            addClickListener(textView,i);
            LinearLayout li = (LinearLayout) getChildAt(getChildCount()-1);
            //LogUtils.w(TAG,"LinearLayout Width:"+li.getMeasuredWidth() +"==== TextView Width :"+textView.getMeasuredWidth());
            int viewWidth = (width == 0 ? DensityUtil.getScreenWidth() : width);
            LogUtils.w("GoodFormatView", "viewWidth : "+(viewWidth-parentPadding));
            if (getWidth(li) + getWidth(textView) > (viewWidth-parentPadding)){
                LogUtils.w(TAG,"添加View,换行");
                //换行
                LinearLayout linearLayout = createLinearLayout();
                linearLayout.addView(textView);
                addView(linearLayout);
            }else {
                LogUtils.w(TAG,"添加View,不换行");
                li.addView(textView);
            }
        }
    }

    private void addClickListener(final TextView view, final int i){
        view.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mListener!=null){
                    if (TextUtil.equals(view.getText(),getAddlastStr())&& i== getDataSize() && haveAddItem){
                        mListener.onLastAddClick();
                    }else {
                        mListener.onItemClick(view,i);
                    }
                }
            }
        });
        view.setOnLongClickListener(new OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                if (mListener!=null){
                    if (!(TextUtil.equals(view.getText(),getAddlastStr())&& i== getDataSize() && haveAddItem)){
                        mListener.onItemLongClick(view,i);
                    }
                }
                return true;
            }
        });
    }

    private int getDataSize() {
        return datas==null?0:datas.size();
    }

    private int getWidth(View view){
        int w = MeasureSpec.makeMeasureSpec(0,
                MeasureSpec.UNSPECIFIED);
        int h = MeasureSpec.makeMeasureSpec(0,
                MeasureSpec.UNSPECIFIED);
        view.measure(w, h);
        LayoutParams layoutParams = (LayoutParams) view.getLayoutParams();
        int rightMargin = 0;
        if (layoutParams != null) {
            rightMargin = layoutParams.rightMargin;
        }
        int width = view.getMeasuredWidth() + rightMargin;

        if (width < minWidth) {
            LogUtils.w("GoodFormatView", "getWidth : "+minWidth);
            return minWidth;
        }
        LogUtils.w("GoodFormatView", "getWidth : "+width);
        return width;
    }

    private void init(Context context){
        setOrientation(LinearLayout.VERTICAL);
        this.mContext = context;
        mTextViewMap = new LongSparseArray<>();
        refreshView();
    }

    private TextView createTextView(){
        TextView  textView = new TextView(mContext);
        LayoutParams textLayoutParams = new LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        textView.setGravity(Gravity.CENTER);
        if (textColor != 0) {
            textView.setTextColor(ContextCompat.getColorStateList(mContext, textColor));
        }else {
            textView.setTextColor(ContextCompat.getColor(mContext, R.color.colorPrimaryBlue));
        }
        textView.setTextSize(TypedValue.COMPLEX_UNIT_SP,10f);
        textLayoutParams.rightMargin = DensityUtil.dip2px(11.5f);
//        int viewWidth = (width == 0 ? DensityUtil.getScreenWidth() : width);
//        textView.setMinWidth((int) ((viewWidth - (DensityUtil.dip2px(57.5f)))/4f));
        textView.setLayoutParams(textLayoutParams);
        textView.setSingleLine(true);
        textView.setPadding(8,6,8,6);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            if (bgResource != 0) {
                textView.setBackground(ContextCompat.getDrawable(mContext, bgResource));
            }else {
//                if (baseScale > 1) {
//                    textView.setBackground(ContextCompat.getDrawable(mContext, R.drawable.selector_goods_format_bg_pad));
//                }else {
                    textView.setBackground(ContextCompat.getDrawable(mContext, R.drawable.shape_bg_blue_stroke));
//                }
            }
        }else {
            if (bgResource != 0) {
                textView.setBackground(ContextCompat.getDrawable(mContext,bgResource));
            }else {
//                if (baseScale > 1) {
//                    textView.setBackground(ContextCompat.getDrawable(mContext, R.drawable.selector_goods_format_bg_pad));
//                }else {
                    textView.setBackground(ContextCompat.getDrawable(mContext, R.drawable.shape_bg_blue_stroke));
//                }
            }
        }
        return textView;
    }

    private LinearLayout createLinearLayout(){
        LinearLayout linearLayout = new LinearLayout(mContext);
        linearLayout.setOrientation(LinearLayout.HORIZONTAL);
        linearLayout.setPadding(DensityUtil.dip2px(11.5f),0,0,0);
        LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
        params.topMargin = DensityUtil.dip2px(5f);
        linearLayout.setLayoutParams(params);
        return linearLayout;
    }

    public void setSelected(int index){
        TextView textView = mTextViewMap.get(index);
        if (textView!=null){
            textView.setSelected(true);
            if (type == 1) {
                for (int i = 0; i < datas.size(); i++) {
                    if ((i != index) && mTextViewMap.get(i) != null) {
                        mTextViewMap.get(i).setSelected(false);
                    }
                }
            }else {
                int isSelectnum = 0;
                for (int i = 0; i<datas.size(); i++){
                    if (datas.get(i).is_select_){
                        isSelectnum++;
                    }
                }
                if (isSelectnum <= getMaxSelect()){
                    if (datas.get(index).is_select_){
                        textView.setSelected(true);
                        datas.get(index).setIs_select_(true);
                    }else {
                        textView.setSelected(false);
                        datas.get(index).setIs_select_(false);
                    }
                }else {
                    textView.setSelected(false);
                    datas.get(index).setIs_select_(false);
//                    ToastUtil.showToast("最多选择"+getMaxSelect()+"个");
                }
            }
        }
    }

    public void cancelSelected(int index){
        TextView textView = mTextViewMap.get(index);
        if (textView!=null){
            textView.setSelected(false);
        }
    }

    public void setOnItemClickListener(OnItemClickListenr listener){
        this.mListener = listener;
    }


    public interface OnItemClickListenr{
        void onItemClick(View view, int index);
        void onLastAddClick();
        void onItemLongClick(View view, int index);
    }
}
